package com.example.tweetfeed;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.example.tweetfeed.LoadImageTask.LoadImageCallback;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class TweetAdapter extends ArrayAdapter<Tweet> implements LoadImageCallback{
	
	private ArrayList<Tweet> mData;
	private Context mContext;
	
	public TweetAdapter(Context context, List<Tweet> objects) {
		super(context, R.layout.tweet_row, objects);
		mData = (ArrayList<Tweet>) objects;
		mContext = context;
	}
		
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) mContext
									.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View rowView = inflater.inflate(R.layout.tweet_row, parent, false);
		fillUIView(rowView, mData.get(position));
		return rowView;
	}
	
	//show twitter feed on UI
	private void fillUIView(View v, Tweet tw) {
		//load containers
		View mLoadingImage = v.findViewById(R.id.load_image);
		View mTweet = v.findViewById(R.id.tweet_all);
		ImageView mTweetUserImage = (ImageView) v.findViewById(R.id.tweet_image);
		TextView mTweetUserName = (TextView) v.findViewById(R.id.tweet_username);
		TextView mTweetText = (TextView) v.findViewById(R.id.tweet_text);
		
		if(tw != null) { //have something to show
			if(tw.getImage() == null) {
			//load image
				mTweetUserImage.setVisibility(View.GONE);
				mLoadingImage.setVisibility(View.VISIBLE);
				new LoadImageTask(this, tw, v).execute(tw.getImageUrl());
			} else {
			//image loaded
				mLoadingImage.setVisibility(View.GONE);
				mTweetUserImage.setImageBitmap(tw.getImage());
				mTweetUserImage.setVisibility(View.VISIBLE);
			}
			//load text
			mTweet.setVisibility(View.VISIBLE);
			mTweetUserName.setText(tw.getUserName());
			mTweetText.setText(tw.getText());
		}
		else { //hide all
			mTweet.setVisibility(View.GONE);
		}
	}

	@Override
	public void onLoadImage(Tweet tw, final View v, final Bitmap img) {
	// check if tweet still exist in list
		if(mData.contains(tw)) {
			tw.setImage(img); //load image
			
		//check view exist to update it with the image
			if(v != null) {
				final Tweet f_tw = tw;
			//fill image on ui
				((MainActivity) mContext).runOnUiThread(new Runnable() {
					@Override
					public void run() {
						fillUIView(v, f_tw);
					}
				});
			}
		}
	}
}
